﻿using UnityEngine;
using System.Collections;

public class AnimateTiledTexture : CharacterAction
{
    public int columns = 5;
    public int rows = 1;
    public GameObject flashObj;
    public bool keepShowing = true;
    public int index = 0;
    public Vector3 localPosition;
    public Vector3 localRotation;

    private MeshRenderer render;

    /*
    void Start()
    {
        StartCoroutine(updateTiling());
        
        //set the tile size of the texture (in UV units), based on the rows and columns
        Vector2 size = new Vector2(1f / columns, 1f / rows);
        renderer.sharedMaterial.SetTextureScale("_MainTex", size);
    }
    
    private IEnumerator updateTiling()
    {
        while (true)
        {
            //move to the next index
            index++;
            if (index >= rows * columns)
                index = 0;
            
            //split into x and y indexes
            Vector2 offset = new Vector2((float)index / columns - (index / columns), //x index
                                         (index / columns) / (float)rows);          //y index
            
            renderer.sharedMaterial.SetTextureOffset("_MainTex", offset);
            
            yield return new WaitForSeconds(1f / framesPerSecond);
        }
    }
    */

    public override void OnActionEnter (Character character)
    {
        base.OnActionEnter(character);
        Vector2 size = new Vector2(1f / columns, 1f / rows);
        render = flashObj.GetComponent<MeshRenderer>();
        render.sharedMaterial.SetTextureScale("_MainTex", size);
        //split into x and y indexes
        Vector2 offset = new Vector2((float)index / columns - (index / columns), //x index
                                     (index / columns) / (float)rows);          //y index
        
        render.sharedMaterial.SetTextureOffset("_MainTex", offset);
        flashObj.SetActive(true);
        flashObj.transform.localPosition = localPosition;
        flashObj.transform.localEulerAngles = localRotation;
    }

    
    public override void OnActionExit (Character character)
    {
        if(!keepShowing)
        {
            flashObj.SetActive(false);
        }
        base.OnActionExit(character);
    }


}
